﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RMS.Web.Shell.View;
using RMS.Utils.MVP;
using RMS.DataAccess.Common;
using RMS.DataAccess.Entities;
using RMS.DataAccess.Repositories;
using System.Web.Security;

namespace RMS.Web.Shell.Presenter
{
    public class LoginPresenter : Presenter<ILoginView>
    {
        #region [ Fields ]
        private readonly EmployeesRepository _employeesRepository;
        private Employees _employees;
        private bool _isActivatedFromConfig;
        #endregion

        #region [ Constructor ]
        public LoginPresenter(EmployeesRepository employeesRepository)
        {
            _employeesRepository = employeesRepository;
        }
        #endregion

        #region [ Methods ]
        public bool EmployeeExists(string username, string password)
        {
            EntityResult<Employees> account = _employeesRepository.Find(items =>
            {
                items.Username = username;
                items.Password = password.Hash();
            });

            if (account.RowCount == 0)
            {
                // check if this user is registered in config if yes save the value for later on else 
                // return false.
                _isActivatedFromConfig = FormsAuthentication.Authenticate(username, password);
                return _isActivatedFromConfig;
            }
            _employees = account.Single();
            return true;
        }

        public bool EmployeeIsNotActive(string username)
        {
            if (_employees == null)
            {
                EntityResult<Employees> account = _employeesRepository.Find(items =>
                {
                    items.Username = username;
                    items.IsActive = false;
                });

                if (account.RowCount == 0)
                    return true;
                _employees = account.Single();
                return false;
            }

            return _employees.IsActive;
        }

        public bool InsertNewPassword(string username, string Pass)
        {
            EmployeeIsNotActive(username);
            if (_employees != null)
            {
                _employees.Password = Pass.Hash();
                _employees.IsActive = true;
                _employeesRepository.Update(_employees);
                return true;
            }
            return false;
        }
        #endregion
    }
}
